package com.uziot.distributed.uaa.service;

import com.uziot.distributed.uaa.dao.domain.SysUser;
import com.uziot.distributed.uaa.dao.mapper.SysMenuMapper;
import com.uziot.distributed.uaa.dao.mapper.SysUserMapper;
import com.uziot.distributed.uaa.service.dto.OauthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className UaaUserDetailsServiceImpl
 * @date 2020-11-28 15:46:46
 * @description 用户详情服务
 */
@Service
public class UaaUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 根据 账号查询用户信息
     *
     * @param username username
     * @return UserDetails
     * @throws UsernameNotFoundException UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //将来连接数据库根据账号查询用户信息
        SysUser sysUser = sysUserMapper.selectUserByUserName(username);
        if (sysUser == null) {
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        //根据用户的id查询用户的权限
        List<String> permissions = sysMenuMapper.selectMenuPermsByUserId(sysUser.getUserId());
        permissions.removeIf(StringUtils::isEmpty);

        //将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        //将userDto转成json
        return new OauthUser(sysUser, permissionArray);
    }
}
